//
//  ContactChatListViewController.m
//  QiFuLianMeng
//
//  Created by yuntai on 2017/4/24.
//  Copyright © 2017年 yuntai. All rights reserved.
//

#import "ContactChatListViewController.h"
#import "ContactChatListViewController+TextViewDelegate.h"
#import "ChartCell.h"
#import "ChatTextMessage.h"
#import "ChatPhotoMessage.h"
#import "GetChatMessage.h"
#import "XMPPMessageArchiveManagement.h"
#import "UcfgroupXMPPManger.h"
#import "XMPPStream.h"
#import "NSString+Time.h"
#import "IWxChatMgrGroup.h"
#import "ChatAudioMessage.h"

#define kMessageListCount       0
static NSString *const cellIdentifier = @"QQChart";

@interface ContactChatListViewController ()<UITableViewDelegate,UITableViewDataSource,ChartCellDelegate,EWxChatMgrChatDelegate,XMPPMessageArchiveManagementDelegate>
@property (nonatomic, assign) NSInteger messageCount;
@property (nonatomic,strong)UIView *bigImageBaseView;//大图的baseView
@property (nonatomic,strong)UIScrollView *bigScroolView;
@property (nonatomic,strong)UIImageView *bigImageView;//显示大图
//加载更多消息
@property (nonatomic, strong) UIView *loadMoreMessageView;

@property (nonatomic, strong) ChartCell *tapChartCell;//点击的cell

@property (nonatomic, strong) XMPPMessageArchiveManagement *messageArchiveManagement;
@property (nonatomic, assign) BOOL isheadrefresh;
@end

@implementation ContactChatListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenBoundWidth,   kNavigationHeight-44)];
    topView.backgroundColor = kNavigationColor;
    [self.view addSubview:topView];
    self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan=NO;
    if (@available(iOS 11.0, *)) {
        
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAlways;
        
    } else {
        
        self.automaticallyAdjustsScrollViewInsets = YES;

    }
    [kUserDefault setObject:self.contactMemID forKey:@"ContactMemId"];
    [kUserDefault setBool:YES forKey:@"IsFristFectch"];
    [kUserDefault synchronize];
    
//    self.automaticallyAdjustsScrollViewInsets = YES;
    
    self.cellFrames = [NSMutableArray array];
    
    [self addTextView];

    [self addTableView];

    //注册消息消息
    [[IWxChatMgrChat sharedInstance] registDelegate:self]; //设置消息代理
    //加载聊天记录
//    self.messageCount = 0;
//    [self loadRecentChatMessageRecord:YES];
//    [self.mainTableView reloadData];
    /**删除聊天记录*/
//    [[IWxChatMgrGroup sharedGroup] deleteAllMessageToContactId:self.contactMemID];

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateProgress:) name:kProgressUpdate object:nil];
    /**删除聊天记录后跟新通知*/
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateChatmessageRecord) name:KupdateChatmessageRecordHLQ object:nil];
    /**下拉刷新*/
    __weak typeof(self)weakself = self;
    MJRefreshNormalHeader *head = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [kUserDefault setBool:NO forKey:@"IsFristFectch"];
        [kUserDefault synchronize];
        weakself.isheadrefresh = YES;
        [weakself.mainTableView.mj_header endRefreshing];
        if (weakself.cellFrames.count ==0) {
            return ;
        }
        ChartCellFrame *cellfrmame = [weakself.cellFrames firstObject];
        NSString *lasttime = [NSString stringTOIMTimeString:cellfrmame.chartMessage.time];
        
        NSString *valuestr = [NSString stringWithFormat:@"%@",[[UcfgroupXMPPManger sharedInstance] convertToJid:weakself.contactMemID]];
        NSXMLElement *field = [XMPPMessageArchiveManagement fieldWithVar:@"with" type:nil andValue:valuestr];
        NSXMLElement *start = [XMPPMessageArchiveManagement  fieldWithVar:@"end" type:nil andValue:lasttime];
        
        XMPPResultSet *resultSet = [XMPPResultSet resultSetWithMax:20 before:@""];
        [weakself.messageArchiveManagement retrieveMessageArchiveWithFields:@[field,start] withResultSet:resultSet];
        
    }];
    head.lastUpdatedTimeLabel.hidden = YES;
    self.mainTableView.mj_header = head;
    
    self.messageArchiveManagement = [[XMPPMessageArchiveManagement alloc] init];
    [self.messageArchiveManagement activate:[UcfgroupXMPPManger sharedInstance].xmppStream];

    NSString *valuestr = [NSString stringWithFormat:@"%@",[[UcfgroupXMPPManger sharedInstance] convertToJid:self.contactMemID]];
    NSXMLElement *field = [XMPPMessageArchiveManagement fieldWithVar:@"with" type:nil andValue:valuestr];
    
    XMPPResultSet *resultSet = [XMPPResultSet resultSetWithMax:20 before:@""];

    [self.messageArchiveManagement retrieveMessageArchiveWithFields:@[field] withResultSet:resultSet];
    [self.messageArchiveManagement addDelegate:self delegateQueue:dispatch_get_main_queue()];

}

- (void)xmppMessageArchiveManagement:(XMPPMessageArchiveManagement *)xmppMessageArchiveManagement didFinishReceivingMessagesWithSet:(XMPPResultSet *)resultSet{
    
    //加载聊天记录
    [self updateChatmessageRecord];
}
- (void)xmppMessageArchiveManagement:(XMPPMessageArchiveManagement *)xmppMessageArchiveManagement didReceiveMAMMessage:(XMPPMessage *)message{
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    /**保存联系惹*/
    [self getUserInfoForAppWithUid:self.contactMemID];
    [[IQKeyboardManager sharedManager]setEnable:NO];

}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager]setEnable:YES];
//    self.navigationController.navigationBar.hidden = YES;

    if (self.tapChartCell) {
        UIImageView *imageView = self.tapChartCell.chartView.messageImageView;
        [imageView stopAnimating];
    }
    [[VoicePlayManager shareInstance]stopVoicePlay];
}

- (void)dealloc
{

    [[IWxChatMgrChat sharedInstance] unregistDelegate:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self.messageArchiveManagement removeDelegate:self];
    [self.messageArchiveManagement deactivate];
    //sendCollectMessageNotification
    [self.textView removeObserver:self forKeyPath:@"y"];
    
}
#pragma mark - UITableViewDelegate,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.cellFrames count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChartCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.isGroup = self.isToRoomChat;
    cell.delegate = self;
    cell.cellFrame = self.cellFrames[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.cellFrames[indexPath.row] cellHeight];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
#warning message -  隐藏键盘 相关and 取消加载更多
    
    if(scrollView != self.bigScroolView){
        [self.textView hideSelfTextView];
        if (scrollView.contentOffset.y < -44) {
            //        [self loadRecentChatMessageRecord:NO];
        }
    }
    if(scrollView == self.mainTableView){
        [[UIMenuController sharedMenuController]setMenuVisible:NO animated:YES];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //    NSLog(@"－scrollViewDidEndDecelerating－scrollView －－－滚动－－");
    
    
}
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if(scrollView == self.bigScroolView){
        return self.bigImageView;
    }
    return nil;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    if(scrollView == self.bigScroolView){
        CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
        (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
        CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
        (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
        self.bigImageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                               scrollView.contentSize.height * 0.5 + offsetY);
        
    }
}
#pragma mark - EWxChatMgrChatDelegate
- (void)sendMessageRspState:(ChatMsgState)state messageId:(NSString *)messageId error:(NSString *)error
{
    WXLog(@"sendMessageRspState state= %d",state);
    if (state == Chat_Send_Success) {
        //发送成功 回调
        for (ChartCellFrame *cellFrame in self.cellFrames) {
            if ([cellFrame.chartMessage.messageId isEqualToString:messageId]) {
                //发送成功使用。
                NSUInteger row = [self.cellFrames indexOfObject:cellFrame];
                cellFrame.chartMessage.sendIsSuccess = Chat_Send_Success;
                [[IWxChatMgrChat sharedInstance] setTheMessageIsSendSuccess:cellFrame.chartMessage.messageId withSendStatus:[NSString stringWithFormat:@"%d", cellFrame.chartMessage.sendIsSuccess]];
                [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:0] ] withRowAnimation:UITableViewRowAnimationNone];
                //发送图片进度使用                
                ChartCell *cell = (ChartCell *)[self.mainTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
                if (cellFrame.chartMessage.messageStyle == kMessageImage) {
                    cell.chartView.contentLabel.text = @"";
                    cell.chartView.contentLabel.hidden = YES;
                    [cell updateCellId:nil isShow:NO];
                    break;
                }
                break;
            }
        }
    }
    else if (state == Chat_Send_Failure)
    {
        //发送失败回调
        for (ChartCellFrame *cellFrame in self.cellFrames) {
            
            if ([cellFrame.chartMessage.messageId isEqualToString:messageId]) {
                //发送消息失败使用。
                cellFrame.chartMessage.sendIsSuccess = Chat_Send_Failure;
                [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:cellFrame.chartMessage.indexNumber.integerValue
                                                                                                       inSection:0]]
                                          withRowAnimation:UITableViewRowAnimationNone];
                //发送图片进度使用
                ChartCell *cell = (ChartCell *)[self.mainTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:cellFrame.chartMessage.indexNumber.integerValue inSection:0]];
                
                if (cellFrame.chartMessage.messageStyle == kMessageImage) {
                    cell.chartView.contentLabel.text = @"";
                    cell.chartView.contentLabel.hidden = YES;
                    [cell updateCellId:nil isShow:NO];
                    break;
                }
                break;
            }
        }
    }else if (state == Chat_Send_Sending){
        
    }else{
        WXLog(@"sendMessageRspState回调信息出错!!!!!");
    }
}

/*!
 @method
 @brief 收到别人发来的新消息回调
 @param msgType     ChatMsgBody_Text         1   //文本类型             message： ChatTextMessage
 ChatMsgBody_Image        2   //图片类型             message： ChatPhotoMessage
 ChatMsgBody_Video        3   //视频类型             message： ChatVideoMessage
 ChatMsgBody_Voice        4   //语音类型             message： ChatAudioMessage
 ChatMsgBody_File         5   //文件类型             message： ChatFileMessage
 ChatMsgBody_SelfDefine,  //大于100为自定义消息类型    message： ChatCustomMessage
 @discussion
 */
- (void)didReceiveMessageType:(NSUInteger)msgType messageObj:(id)message;
{
    if (message == nil) {
        return;
    }
    ChartCellFrame *cellFrame = [[ChartCellFrame alloc] init];
    ChartMessage *chartMessage = [[ChartMessage alloc] init];
    NSString *previousTimeStr = nil;
    ChartCellFrame *previousChartCellFrame = nil;
    if (self.cellFrames.count != 0) {
        previousChartCellFrame = (ChartCellFrame *)[self.cellFrames lastObject];
        previousTimeStr = previousChartCellFrame.chartMessage.time;
    }
    chartMessage.messageType = kMessageFrom;
    
    NSString *bodyStr = nil;
    NSString *timeStr = nil;
    switch (msgType) {
        case ChatMsgBody_Prompt:
        case ChatMsgBody_Text:
        {
            ChatTextMessage *msg       = (ChatTextMessage *)message;
            bodyStr                    = msg.textMessage;
            timeStr                    = msg.createTime;
            chartMessage.messageStyle  = kMessageText;
            chartMessage.isGroupMsg    = msg.isGroupMsg;
            chartMessage.fromMemID     = msg.fromMemberID;
            chartMessage.fromContactID = msg.contactId;
            chartMessage.messageId = msg.messageId;
            
            BOOL ret = [self matchingChat:msg.isGroupMsg withChatId:msg.contactId];
            if (!ret) {
                return;
            }
            [[IWxChatMgrChat sharedInstance] setTheMessageIsReaded:msg.messageId];//将消息置为已读
        }
            break;
        case ChatMsgBody_Image:
        {
            ChatPhotoMessage *msg = (ChatPhotoMessage *)message;
            bodyStr = msg.fileName;
            timeStr = msg.createTime;
            chartMessage.messageImageUrl = msg.localFileUrl;
            chartMessage.messageImageBigUrl = msg.localFileUrl;
            chartMessage.messageStyle = kMessageImage;
            chartMessage.isGroupMsg = msg.isGroupMsg;
            chartMessage.fromMemID = msg.fromMemberID;
            chartMessage.messageId = msg.messageId;
            chartMessage.fromContactID = msg.contactId;
            chartMessage.messageId = msg.messageId;
            
            chartMessage.fileName = msg.fileName;
            BOOL ret = [self matchingChat:msg.isGroupMsg withChatId:msg.contactId];
            if (!ret) {
                return;
            }
            [[IWxChatMgrChat sharedInstance] setTheMessageIsReaded:msg.messageId];//将消息置为已读
            
        }
            break;
        case ChatMsgBody_Voice:
        {
            ChatAudioMessage *msg      = (ChatAudioMessage *)message;
            bodyStr                    = @"这是语音文件";
            timeStr                    = msg.createTime;
            chartMessage.messageStyle  = kMessageAudio;
            chartMessage.duration      = msg.duration;
            chartMessage.fileName      = msg.fileName;
            chartMessage.isGroupMsg    = msg.isGroupMsg;
            chartMessage.fromMemID     = msg.fromMemberID;
            chartMessage.fromContactID = msg.contactId;
            chartMessage.isRead        = YES;
            chartMessage.messageId = msg.messageId;
             [[IWxChatMgrChat sharedInstance] setTheMessageIsReaded:msg.messageId];
            BOOL ret = [self matchingChat:msg.isGroupMsg withChatId:msg.contactId];
            if (!ret) {
                return;
            }
           
            
        }
            break;
        default:
            NSAssert(0, @"消息类型错误！！！");
            break;
    }
    
    chartMessage.content = bodyStr;
    chartMessage.time = [NSString stringWithPreviousTime:previousTimeStr withLatterTime:timeStr];
    //[self getFormatTime:timeStr];
    cellFrame.chartMessage = chartMessage;
    
    [self.cellFrames addObject:cellFrame];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(self.cellFrames.count-1) inSection:0];
    [self.mainTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
    //滚动到当前行
    [self tableViewScrollCurrentIndexPath];
}
/*!
 @method
 @brief 对方（好友）收到消息的回调
 @param message      消息对象
 @discussion 触发
 */
- (void)didRecipientRecieved:(NSString *)msgId recipientId:(NSString *)recipientId
{
    for (ChartCellFrame *cellFrame in self.cellFrames) {
        if ([cellFrame.chartMessage.messageId isEqualToString:msgId]) {
            //对方接受成功
            cellFrame.chartMessage.sendIsSuccess = Chat_Receive_Success;
            
            [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:cellFrame.chartMessage.indexNumber.integerValue
                                                                                                   inSection:0]]
                                      withRowAnimation:UITableViewRowAnimationFade];
            break;
        }
    }
}

#pragma mark -  IChatProgressDelegate
/*!
 @method
 @brief 设置进度
 @discussion 用户需实现此接口用以支持进度显示
 @param progress 值域为0到1.0的浮点数
 @param message  某一条消息的progress
 @result
 */
- (void)setProgress:(float)progress forMessage:(NSString *)messageId
{
    NSLog(@"setProgress--progress= %f",progress);
    for (ChartCellFrame *cellFrame in self.cellFrames) {
        if ([cellFrame.chartMessage.messageId isEqualToString:messageId]) {
            //发送图片进度使用
            NSUInteger row = [self.cellFrames indexOfObject:cellFrame];
            ChartCell *cell = (ChartCell *)[self.mainTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
            if (cellFrame.chartMessage.messageStyle == kMessageImage) {
                if (cell.chartView.contentLabel.hidden) {
                    [cell updateCellId:nil isShow:YES];
                    cell.chartView.contentLabel.hidden = NO;
                }
                cell.chartView.contentLabel.text = [NSString stringWithFormat:@"%.0f%@", progress*100, @"%"];
                break;
            }
            break;
        }
    }
}
#pragma mark - VoicePlayManagerDelegate
/**
 *  结束播放
 *
 *  @param voicePlayManager
 */
- (void)voiceEndPlayVoicePlayManager:(VoicePlayManager *)voicePlayManager
{
    UIImageView *imageView = self.tapChartCell.chartView.messageImageView;
    [imageView stopAnimating];
    if (self.tapChartCell.chartView.chartMessage.messageType == kMessageFrom ) {
        NSIndexPath *indexPath = [self.mainTableView indexPathForCell:self.tapChartCell];
        if ((indexPath)) {
            [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                                      withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

#pragma mark - ChartCellDelegate
/**
 *  点击事件
 *
 *  @param chartCell
 *  @param content
 */
-(void)chartCell:(ChartCell *)chartCell tapContent:(NSString *)content
{
    [self.textView hideSelfTextView];
    if (content == nil) {
        
        return;
    }
    if (self.tapChartCell) {
        UIImageView *imageView = self.tapChartCell.chartView.messageImageView;
        [imageView stopAnimating];
    }
    self.tapChartCell = chartCell;
    
    if (chartCell.chartView.chartMessage.messageStyle == kMessageImage) {
        //点击的是图片消息
        [KeyWindow addSubview:self.bigImageBaseView];
        NSString *localFilePathName = [NSString wbChatPathWithType:kChatMsgBody_Image];
        localFilePathName = [NSString stringWithFormat:@"%@/%@",localFilePathName,content];
        if ([[NSFileManager defaultManager] fileExistsAtPath:localFilePathName]) {
            NSFileManager* manager    = [NSFileManager defaultManager];
            NSData *imageData         = [manager contentsAtPath:localFilePathName];
            self.bigImageView.image = [UIImage imageWithData:imageData];
        }else{
            [self.bigImageView sd_setImageWithURL:[NSURL URLWithString:content]];
        }
    }
    if (chartCell.chartView.chartMessage.messageStyle == kMessageAudio) {
        
        UIImageView *imageView = self.tapChartCell.chartView.messageImageView;
        [imageView startAnimating];
        [VoicePlayManager shareInstance].delegate = self;
        if (chartCell.chartView.chartMessage.messageType == kMessageFrom) {
            [[VoicePlayManager shareInstance]preparePlayWithConnectUrlStr:content];
            chartCell.cellFrame.chartMessage.isRead = YES;
            [[IWxChatMgrChat sharedInstance] setTheMessageIsReaded:chartCell.cellFrame.chartMessage.messageId];//将消息置为已读
        }else{
            if ([content hasPrefix:@"http://tianjiu.oss"]) {
                [[VoicePlayManager shareInstance]preparePlayWithConnectUrlStr:content];
            }else{
                //播放本地音频
                [[VoicePlayManager shareInstance]preparePlayWithFilePath:content];
            }
           
        }
    }
}
/**
 *  长按事件
 *
 *  @param chartCell    cell
 *  @param chartMessage 对应的message
 *  @param longTapType  长按之后的类型
 */
- (void)longTapChartCell:(ChartCell *)chartCell
            chartMessage:(ChartMessage *)chartMessage
    chartCellLongTapType:(ChartCellLongTapType)longTapType
{

    
}

#pragma mark - Private methods
-(void)getUserInfoForAppWithUid:(NSString *)uids{
//    NSDictionary *param = @{@"uids":uids};
//    __weak typeof(self)weakself = self;
//    [NetWork PostNetWorkWithUrl:KappAllUserForApp with:param successBlock:^(NSDictionary *dic) {
//        NSArray *temparray = dic[@"dataobj"];
//        if (temparray.count) {
//         
//            NSDictionary *tempdic = [temparray firstObject];
//            ContactMemModel *model = [ContactMemModel mj_objectWithKeyValues:tempdic];
//            weakself.title = weakself.contactMemName = model.userName?:weakself.title;
////            [ChatContactMgr saveContactMemModel:model];
//            
//
//        }
//        
//    } FailureBlock:^(NSString *msg) {
//        
//    } errorBlock:^(id error) {
//        
//    }];
    ContactMemModel *model = [[ContactMemModel alloc]init];
    model.ContactId = self.contactMemID;
    model.userName = self.contactMemName;
    [ChatContactMgr saveContactMemModel:model];


}


- (void)updateProgress:(NSNotification*)notification
{
    id obj = [notification object];//获取到传递的对象
    
    if ([obj isKindOfClass:[NSMutableDictionary class]])
    {
        NSMutableDictionary *progressDic = obj;
        NSString *newProgress = [progressDic objectForKey:@"newProgress"];
        NSString *msgId = [progressDic objectForKey:@"msgId"];
        [self setProgress:[newProgress floatValue] forMessage:msgId];
    }
}
-(void)updateChatmessageRecord{
    //加载聊天记录
    [self.cellFrames removeAllObjects];
    [self.mainTableView reloadData];
    self.messageCount = 0;
    [self loadRecentChatMessageRecord:YES];
}
// 添加tableView
- (void)addTableView
{
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavigationHeight, kScreenBoundWidth, kScreenBoundHeight - 44 - kNavigationHeight) style:UITableViewStylePlain];
    self.mainTableView.backgroundColor = [UIColor clearColor];
    self.mainTableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    self.mainTableView.delegate        = self;
    self.mainTableView.dataSource      = self;
    [self.mainTableView registerClass:[ChartCell class] forCellReuseIdentifier:cellIdentifier];
    [self.view addSubview:self.mainTableView];
}

/**
 *  滚动到当前行
 */
-(void)tableViewScrollCurrentIndexPath
{
    if (self.cellFrames.count == 0) {
        return;
    }
    if (!self.isheadrefresh) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.cellFrames.count - 1 inSection:0];
        [self.mainTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
    self.isheadrefresh = NO;
   
}
//匹配消息对象（匹配聊天室，匹配个人）
- (BOOL)matchingChat:(BOOL)isGroupMsg withChatId:(NSString *)chatIdString
{
    NSString *chatId = nil;
    if (isGroupMsg == YES) {

    }
    else
    {
        chatId = self.contactMemID;
    }
    if (self.isToRoomChat == isGroupMsg && [chatId isEqualToString:chatIdString])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//聊天记录的获取
- (void)loadRecentChatMessageRecord:(BOOL)isInit
{
    NSMutableArray *chatRecordArray = nil;
    //    self.messageCount = self.cellFrames.count;
    if (self.isToRoomChat) {
        chatRecordArray = [[IWxChatMgrChat sharedInstance] fetchMessageListWithUser:self.contactMemID beginIndex:self.messageCount count:kMessageListCount];
    }
    else
    {
        chatRecordArray = [[IWxChatMgrChat sharedInstance] fetchMessageListWithUser:self.contactMemID beginIndex:self.messageCount count:kMessageListCount];
    }
    
//    NSArray *array =  [[chatRecordArray reverseObjectEnumerator] allObjects];
    
    [self loadRecentChatMessageRecordWithDataArray:chatRecordArray withIsInit:isInit];
}
- (void)loadRecentChatMessageRecordWithDataArray:(NSMutableArray *)chatRecordArray withIsInit:(BOOL)isInit
{
    
    for (NSInteger i = 0 ;i < chatRecordArray.count; i ++) {
        GetChatMessage *getmessage = [chatRecordArray objectAtIndex:i];
        GetChatMessage *previousGetMessage = nil;
        ChartCellFrame *cellFrame=[[ChartCellFrame alloc] init];
        ChartMessage *chartMessage=[[ChartMessage alloc] init];
        NSString *bodyStr = nil;
        //  NSString *senderStr = message.toId;
        NSString *timeStr = nil;
        NSString *previousTimeStr = nil;
        if (i != 0) {
            for (NSInteger j = i; j > 0; j --) {
                previousGetMessage = [chatRecordArray objectAtIndex:j - 1];
                switch (getmessage.messageType) {
                    case ChatMsgBody_Prompt:
                    case ChatMsgBody_Text:
                    {
                        ChatTextMessage *previousMsg = (ChatTextMessage *)previousGetMessage.message;
                        previousTimeStr = previousMsg.createTime;
                    }
                        break;
                   
                    case ChatMsgBody_Image:
                    {
                        ChatPhotoMessage *previousMsg = (ChatPhotoMessage *)previousGetMessage.message;
                        previousTimeStr = previousMsg.createTime;
                    }
                        break;
                    case ChatMsgBody_Voice:
                    {
                        ChatAudioMessage *previousMsg = (ChatAudioMessage *)previousGetMessage.message;
                        previousTimeStr = previousMsg.createTime;
                    }
                        break;
                    
                    default:
                        break;
                }
                if (previousTimeStr) {
                    break;
                }
                
            }
        }else{
            previousTimeStr = [NSString stringFromNSDate:[NSDate  date]];
        }
        switch (getmessage.messageType) {
            case ChatMsgBody_Prompt:
            case ChatMsgBody_Text:
            {   
                ChatTextMessage *msg = (ChatTextMessage *)getmessage.message;
                chartMessage.messageId = msg.messageId;
                chartMessage.fromContactID = msg.contactId;
                chartMessage.fromMemID = msg.fromMemberID;
                chartMessage.isGroupMsg = msg.isGroupMsg;
                if (msg.isIncoming == Msg_In) {
                    chartMessage.messageType = kMessageFrom;
                    if (!msg.isRead) {
                        [[IWxChatMgrChat sharedInstance] setTheMessageIsReaded:msg.messageId];
                    }
                }
                else
                {
                    chartMessage.messageType = kMessageTo;
                    chartMessage.sendIsSuccess = (ChatMsgState)msg.messageStatus;
                }
                bodyStr = msg.textMessage;
                timeStr = msg.createTime;
                chartMessage.messageStyle = kMessageText;
            }
                break;
            case ChatMsgBody_Image:
            {
                ChatPhotoMessage *msg = (ChatPhotoMessage *)getmessage.message;
                chartMessage.messageId = msg.messageId;
                chartMessage.fromContactID = msg.contactId;
                chartMessage.fromMemID = msg.fromMemberID;
                chartMessage.isGroupMsg = msg.isGroupMsg;
                
                if (msg.isIncoming==Msg_In) {
                    chartMessage.messageType = kMessageFrom;
                    chartMessage.messageImageUrl = msg.localFileUrl;
                    if (!msg.isRead) {
                        [[IWxChatMgrChat sharedInstance] setTheMessageIsReaded:msg.messageId];
                    }
                }
                else
                {
                    chartMessage.messageType = kMessageTo;
                    chartMessage.sendIsSuccess = (ChatMsgState)msg.messageStatus;
                    chartMessage.messageImageUrl = msg.localFileUrl;
                }
                chartMessage.fileName = msg.fileName;
                timeStr = msg.createTime;
                chartMessage.messageStyle = kMessageImage;
            }
                break;
            case ChatMsgBody_Voice:
            {
                // 语音的标记为已读 需要等到播放之后才标记！！！！！
                ChatAudioMessage *msg = (ChatAudioMessage *)getmessage.message;
                chartMessage.messageId = msg.messageId;
                chartMessage.fromContactID = msg.contactId;
                chartMessage.fromMemID = msg.fromMemberID;
                chartMessage.isGroupMsg = msg.isGroupMsg;
                
                if (msg.isIncoming == Msg_In) {
                    chartMessage.messageType = kMessageFrom;
                    if (!msg.isRead) {
                                                [[IWxChatMgrChat sharedInstance] setTheMessageIsReaded:msg.messageId];
                    }
                    chartMessage.isRead = msg.isRead;
                    chartMessage.fileName = msg.localFileUrl;
                    
                }
                else
                {
                    chartMessage.fileName = msg.fileName;
                    chartMessage.messageType = kMessageTo;
                    chartMessage.sendIsSuccess = (ChatMsgState)msg.messageStatus;
                    
                }
                bodyStr = msg.fileName;
                timeStr = msg.createTime;
                chartMessage.duration = msg.duration;
                chartMessage.messageStyle = kMessageAudio;
            }
                break;

            default:
                break;
        }
        
        chartMessage.content = bodyStr;
        chartMessage.time = timeStr;
        chartMessage.showTime = [NSString stringWithPreviousTime:previousTimeStr withLatterTime:timeStr];
        cellFrame.chartMessage = chartMessage;
        
        [self.cellFrames insertObject:cellFrame atIndex:0];
        [self.mainTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0  inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
    }
    if (isInit) {
        [self tableViewScrollCurrentIndexPath];
    }
}

#pragma mark - setter
- (UIView *)loadMoreMessageView
{
    if (!_loadMoreMessageView) {
        _loadMoreMessageView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenBoundWidth, 44)];
        _loadMoreMessageView.backgroundColor = [UIColor clearColor];
        UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenBoundWidth, 44)];
        tipLabel.backgroundColor = [UIColor clearColor];
        tipLabel.text = @"下拉加载更多消息";
        tipLabel.font = [UIFont fontWithName:@"Helvetica" size:12.0];
        tipLabel.textColor = [UIColor blackColor];
        tipLabel.textAlignment = NSTextAlignmentCenter;
        
        [_loadMoreMessageView addSubview:tipLabel];
        
    }
    return _loadMoreMessageView;
}

- (UIView *)bigImageBaseView
{
    if (!_bigImageBaseView) {
        _bigImageBaseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenBoundWidth, kScreenBoundHeight)];
        _bigImageBaseView.backgroundColor = [UIColor blackColor];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self
                                                                                    action:@selector(bigBaseImageViewAction)];
        [_bigImageBaseView addGestureRecognizer:tapGesture];
        
        self.bigScroolView = [[UIScrollView alloc]initWithFrame:_bigImageBaseView.bounds];
        self.bigScroolView.maximumZoomScale = 2.0;
        self.bigScroolView.minimumZoomScale = 0.5;
        self.bigScroolView.delegate = self;
        [_bigImageBaseView addSubview:self.bigScroolView];
        self.bigScroolView.center = _bigImageBaseView.center;
        self.bigImageView = [[UIImageView alloc]initWithFrame:self.bigScroolView.bounds];
        self.bigImageView.layer.masksToBounds = YES;
        self.bigImageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.bigScroolView addSubview:self.bigImageView];
        self.bigImageView.center = self.bigScroolView.center;
        
        //暂时隐藏
        CGFloat btnWidth = 60;
        UIButton *saveImageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        saveImageBtn.backgroundColor = [UIColor clearColor];
        saveImageBtn.frame = CGRectMake(20, kScreenBoundHeight - 100, btnWidth, btnWidth);
        saveImageBtn.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [saveImageBtn setImage:[UIImage imageNamed:@"MJPhotoBrowser.bundle/save_icon.png"] forState:UIControlStateNormal];
        [saveImageBtn setImage:[UIImage imageNamed:@"MJPhotoBrowser.bundle/save_icon_highlighted.png"] forState:UIControlStateHighlighted];
        [saveImageBtn addTarget:self action:@selector(saveImage) forControlEvents:UIControlEventTouchUpInside];
        [_bigImageBaseView addSubview:saveImageBtn];
        
        
        
    }
    return _bigImageBaseView;
}
- (void)bigBaseImageViewAction
{
    [self.bigImageBaseView removeFromSuperview];
    self.bigScroolView.zoomScale = 1.0;
}
- (void)saveImage
{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImageWriteToSavedPhotosAlbum(self.bigImageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    });
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        [HUDManager showWarningWithText:@"保存失败"];
    } else {
        
        [HUDManager showWarningWithText:@"成功保存到相册"];
    }
}
#pragma mark - SETTERS
- (TFRecorder *)audioRecorder
{
    if (_audioRecorder == nil) {
        self.audioRecorder = [[TFRecorder alloc] init];
        [self setAudioSession];
    }
    return _audioRecorder;
}
// 设置音频会话
- (void)setAudioSession
{
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
}

@end
